

/*********************** Date扩展 开始 create by 浩安********************/
(function () {

    if (window._my_ext_flg) {
        return;
    }
    window._my_ext_flg = true;

    //日期格式化
    Date.prototype.Format = function (formatStr) {
        var str = formatStr ? formatStr : "yyyy-MM-dd";
        var week = ['日', '一', '二', '三', '四', '五', '六'];
        var date = this;
        str = str.replace(/yyyy|YYYY/, date.getFullYear());
        str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : '0' + (date.getYear() % 100));

        str = str.replace(/MM/, date.getMonth() > 8 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1));
        str = str.replace(/M/g, date.getMonth() + 1);

        str = str.replace(/w|W/g, week[date.getDay()]);

        str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
        str = str.replace(/d|D/g, date.getDate());

        str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
        str = str.replace(/h|H/g, date.getHours());
        str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());
        str = str.replace(/m/g, date.getMinutes());

        str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds());
        str = str.replace(/s|S/g, date.getSeconds());

        return str;
    };

    //日期贝拷贝拷
    Date.prototype.Clone = function () {
        return new Date(this.getTime());
    };

    //字符串解析为Date
    Date.Parse = function (dateStr) {
        if (!dateStr) {
            return null;
        }
        if (dateStr.constructor === new Date().constructor) {
            return dateStr;
        }
        var date = dateStr.replace(/(-|\.)/g, '/');
        return new Date(date);
    };

    //得到某月的天数
    Date.GetMonthDays = function (month, year) {
        var date = new Date();
        //var month = arguments[0];
        var year = year ? year : date.getFullYear();
        var now = new Date(year, month - 1, 1);
        var next = new Date(year, month, 1);
        return (next - now).ToDay();
    };

    //增加天数
    Date.prototype.AddDays = function (days) {
        this.setDate(this.getDate() + days);
        return this;
    };

    //增加月
    Date.prototype.AddMonths = function (months) {
        this.setMonth(this.getMonth() + months);
        return this;
    };

    //增加年
    Date.prototype.AddYears = function (years) {
        this.setFullYear(this.getFullYear() + years);
        return this;
    };

    //得到当前日期所在周的周一
    Date.prototype.GetFirstDayOfWeek = function () {
        var dayOfWeek = this.getDay();
        var delat = 0;
        if (dayOfWeek == 0) {
            delat = 7;
        }
        this.setDate(this.getDate() - dayOfWeek + 1 - delat);
        return this;
    };

    //格式化快捷
    Date.prototype.yyyyMMdd = function () {
        return this.Format('yyyyMMdd');
    }
    Date.prototype.yyyy_MM_dd = function () {
        return this.Format('yyyy-MM-dd');
    }
    Date.prototype.yyyyMMddHHmmss =function(){
        return this.Format('yyyyMMddHHmmss');
    };
    Date.prototype.yyyy_MM_dd_HH_mm_ss =function(){
        return this.Format('yyyy-MM-dd HH:mm:ss');
    };


})();
/*********************** Date扩展 结束********************/

//获取唯一序列
function getUniqueID() {
    var count_id = 1;
    var base_id = 'id_' + new Date().getTime() + '_';
    getUniqueID = function () {
        return base_id + count_id++;
    };
    return getUniqueID();
}


//URL参数解析
(function () {
    if (window.ParseUrl) {
        return;
    }
    //解析URL
    window.ParseUrl = function (url) {
        url += '';
        var arr = url.split('?');
        var params = {};
        params.get = function (name, default_value) {
            if (typeof (default_value) == 'undefined') {
                default_value = '';
            }
            if ($.inArray(name, Object.keys(this)) <= -1) {
                return default_value;
            }

            return this[name] == '' ? default_value : this[name];
        };
        if (arr.length <= 1) {
            //return params;
            arr = arr[0].split('&');
        } else {
            arr = arr[1].split('&');
        }


        for (var i = 0; i < arr.length; i++) {
            var a = arr[i].split('=');
            params[a[0]] = a[1];
        }

        return params;
    };

    //将encode后的参数转为JSON格式字符串
    window.QueryParamsToPostData = function (url) {
        return JSON.stringify(ParseUrl(decodeURIComponent(url)));
    };

})();


//throttle和debounce
(function () {
    if (window.__throttle_flg) {
        return;
    }
    window.__throttle_flg=true;
    var debounceOptions = {
        'leading': false,
        'maxWait': 0,
        'trailing': false
    };
    var now = function () {
        return new Date().getTime();
    };

    //throttle
    function throttle(func, wait, options) {
        var leading = true,
            trailing = true;

        if (typeof func != 'function') {
            throw new TypeError('不是function');
        }
        if (options === false) {
            leading = false;
        } else if ($.isPlainObject(options)) {
            leading = 'leading' in options ? !!options.leading : leading;
            trailing = 'trailing' in options ? !!options.trailing : trailing;
        }
        debounceOptions.leading = leading;
        debounceOptions.maxWait = +wait;
        debounceOptions.trailing = trailing;
        return debounce(func, wait, debounceOptions);
    }

    //debounce
    function debounce(func, wait, options) {
        var args,
            maxTimeoutId,
            result,
            stamp,
            thisArg,
            timeoutId,
            trailingCall,
            lastCalled = 0,
            maxWait = false,
            trailing = true;

        if (typeof func != 'function') {
            throw new TypeError('不是function');
        }
        wait = wait < 0 ? 0 : (+wait || 0);
        if (options === true) {
            var leading = true;
            trailing = false;
        } else if ($.isPlainObject(options)) {
            leading = options.leading;
            maxWait = 'maxWait' in options && Math.max(+options.maxWait || 0, wait);
            trailing = 'trailing' in options ? options.trailing : trailing;
        }

        function cancel() {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
            if (maxTimeoutId) {
                clearTimeout(maxTimeoutId);
            }
            maxTimeoutId = timeoutId = trailingCall = undefined;
        }

        function delayed() {
            var remaining = wait - (now() - stamp);
            if (remaining <= 0 || remaining > wait) {
                if (maxTimeoutId) {
                    clearTimeout(maxTimeoutId);
                }
                var isCalled = trailingCall;
                maxTimeoutId = timeoutId = trailingCall = undefined;
                if (isCalled) {
                    lastCalled = now();
                    result = func.apply(thisArg, args);
                    if (!timeoutId && !maxTimeoutId) {
                        args = thisArg = null;
                    }
                }
            } else {
                timeoutId = setTimeout(delayed, remaining);
            }
        }

        function maxDelayed() {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
            maxTimeoutId = timeoutId = trailingCall = undefined;
            if (trailing || (maxWait !== wait)) {
                lastCalled = now();
                result = func.apply(thisArg, args);
                if (!timeoutId && !maxTimeoutId) {
                    args = thisArg = null;
                }
            }
        }

        function debounced() {
            args = arguments;
            stamp = now();
            thisArg = this;
            trailingCall = trailing && (timeoutId || !leading);

            if (maxWait === false) {
                var leadingCall = leading && !timeoutId;
            } else {
                if (!maxTimeoutId && !leading) {
                    lastCalled = stamp;
                }
                var remaining = maxWait - (stamp - lastCalled),
                    isCalled = remaining <= 0 || remaining > maxWait;

                if (isCalled) {
                    if (maxTimeoutId) {
                        maxTimeoutId = clearTimeout(maxTimeoutId);
                    }
                    lastCalled = stamp;
                    result = func.apply(thisArg, args);
                }
                else if (!maxTimeoutId) {
                    maxTimeoutId = setTimeout(maxDelayed, remaining);
                }
            }
            if (isCalled && timeoutId) {
                timeoutId = clearTimeout(timeoutId);
            }
            else if (!timeoutId && wait !== maxWait) {
                timeoutId = setTimeout(delayed, wait);
            }
            if (leadingCall) {
                isCalled = true;
                result = func.apply(thisArg, args);
            }
            if (isCalled && !timeoutId && !maxTimeoutId) {
                args = thisArg = null;
            }
            return result;
        }
        debounced.cancel = cancel;
        return debounced;
    }

    window.throttle = throttle;
    window.debounce = debounce;
})();


//delay
(function(){

    if(window.__delay_flg){
        return;
    }
    window.__delay_flg=true;

    //延迟
    //用法：delay(1000).done(()=>console.log('1000ms had gone'));
    window.delay = function (ms) {
        var defer = $.Deferred();
        defer.delay = arguments.callee;
        if (this.done && $.isFunction(this.done)) {//等上个Deferred执行完后再执行延迟
            this.done(function () {
                setTimeout(function () {
                    defer.resolve();
                }, ms);
            });
        } else{
            setTimeout(function () {
                defer.resolve();
            }, ms);
        }
    
        return defer;
    };


})();
